# \zennotac-backend\app\services\exceling_pdf.py
import os
from pathlib import Path
from datetime import datetime
from app.services.pdf_processing import process_pdf
from app.config.base_setting import OCR_OUTPUT_FOLDER
from app.services.progress_service import (
    start_task,
    update_task,
    complete_task,
    fail_task
)
import uuid

FIXED_EXCEL_FILENAME = "autofill_input.xlsx"

def generate_excel_from_text(input_path: str) -> dict:
    """
    Convert OCR-ed PDF (text) to Excel. Returns metadata with task progress ID.
    """
    return _run_excel_generation(input_path, mode="text")


def generate_excel_from_table(input_path: str) -> dict:
    """
    Convert OCR-ed PDF (table) to Excel. Returns metadata with task progress ID.
    """
    return _run_excel_generation(input_path, mode="table")


def _run_excel_generation(input_path: str, mode: str) -> dict:
    """
    Internal shared logic for generating Excel from OCRed PDF.
    Mode can be 'text' or 'table' for suffix purposes only.
    """
    task_id = str(uuid.uuid4())
    start_time = datetime.utcnow()
    suffix = "_structured_text" if mode == "text" else "_structured_table"

    try:
        start_task(task_id, total_steps=3, label=f"Starting Excel generation ({mode})")

        update_task(task_id, 1, label="Parsing PDF and extracting content")
        output_dir = Path(OCR_OUTPUT_FOLDER)
        output_path = output_dir / FIXED_EXCEL_FILENAME

        process_pdf(input_path, suffix=suffix, output_excel_path=str(output_path))

        update_task(task_id, 2, label="Writing Excel output")

        if not output_path.exists():
            raise FileNotFoundError(f"Excel file not found: {output_path}")

        update_task(task_id, 3, label="Completed")
        complete_task(task_id)

        return {
            "generated_file": output_path.name,
            "task_id": task_id,
            "source_file": Path(input_path).name,
            "generated_at": datetime.utcnow().isoformat(),
            "processing_time": f"{(datetime.utcnow() - start_time).total_seconds():.2f}s"
        }

    except Exception as e:
        fail_task(task_id, str(e))
        raise e



# import os
# from pathlib import Path
# from app.services.pdf_processing import process_pdf
# from app.config.base_setting import OCR_OUTPUT_FOLDER

# FIXED_EXCEL_FILENAME = "autofill_input.xlsx"

# def generate_excel_from_text(input_path: str) -> str:
#     """
#     Convert OCR-ocred PDF (text content) to Excel.
#     Uses fixed filename for automation in Stage 3.
#     """
#     output_dir = Path(OCR_OUTPUT_FOLDER)
#     output_path = output_dir / FIXED_EXCEL_FILENAME

#     # internally, you can use `suffix="_structured_text"` if needed
#     process_pdf(input_path, suffix="_structured_text", output_excel_path=str(output_path))
#     return str(output_path)


# def generate_excel_from_table(input_path: str) -> str:
#     """
#     Convert OCR-ocred PDF (table content) to Excel.
#     Also uses fixed filename.
#     """
#     output_dir = Path(OCR_OUTPUT_FOLDER)
#     output_path = output_dir / FIXED_EXCEL_FILENAME

#     # suffix is just a flag in your PDF parser, actual output name is fixed
#     process_pdf(input_path, suffix="_structured_table", output_excel_path=str(output_path))
#     return str(output_path)
